package com.bachongLightNovel.message.listener;

import com.alibaba.fastjson2.JSON;
import com.bachongLightNovel.constant.MessageConstant;
import com.bachongLightNovel.constant.RabbitmqConstant;
import com.bachongLightNovel.message.mapper.MessageMapper;
import com.bachongLightNovel.model.pojo.message.Message;
import com.bachongLightNovel.works.IWorksNovelClient;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

/**
 * @author vermouth
 */

@Component
@Slf4j
public class RabbitmqListener {

    @Autowired
    private MessageMapper messageMapper;




//    @RabbitListener(
//            bindings = {
//                    @QueueBinding(value = @Queue(value = RabbitmqConstant.BACHONG_MESSAGE_QUEUE,durable = "true"),
//                    exchange = @Exchange(value = RabbitmqConstant.BACHONG_MESSAGE_EXCHANGE),
//                    key = RabbitmqConstant.BACHONG_MESSAGE_KEY)
//            }
//    )
    @RabbitListener(queues = RabbitmqConstant.BACHONG_MESSAGE_QUEUE)
    @Transactional
    public void messageListener(String jsonMessage, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag){
        try {
            log.info("接收到消息：{}",jsonMessage);
            Message message = JSON.parseObject(jsonMessage, Message.class);
            //将消息插入到数据库当中
            messageMapper.insert(message);
            //确认消息消费成功
            channel.basicAck(tag,false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
